from django.shortcuts import render,redirect
from django.core.paginator import Paginator
from app.models import Book,User
from django.contrib.auth import login,authenticate
from django.contrib.auth.decorators import login_required
# Create your views here.
# 展示
@login_required
def Index(request):
    book=Book.objects.all()
    page=int(request.GET.get('page',1))
    p=Paginator(book,2)
    current_page = p.get_page(page)
    num = p.num_pages
    pre_page = current_page.number - 1
    next_page = current_page.number + 1
    return render(request,'index.html',{'current_page':current_page.object_list,
                                        'current_num':current_page.number,
                                        'num':num,
                                        'pre_page':pre_page,
                                        'next_page':next_page,})
# 添加
def book_add(request):
    if request.method=='POST':
       title=request.POST.get('title')
       createTime=request.POST.get('createTime')
       author=request.POST.get('author')
       titles = Book.objects.filter(title=title)
       if titles:
           return render(request,'add.html',{'error':'此标题已存在，请重新添加'})
       Book.objects.create(title=title,createTime=createTime,author=author)
       return redirect('index')
    return render(request,'add.html')
# 搜索
def search(request):
    if request.method=='POST':
        name=request.POST.get('name')
        book=Book.objects.filter(title__contains=name)
        page = int(request.GET.get('page', 1))
        p = Paginator(book, 2)
        current_page = p.get_page(page)
        num = p.num_pages
        pre_page = current_page.number - 1
        next_page = current_page.number + 1
        return render(request, 'search.html', {'current_page': current_page.object_list,
                                              'current_num': current_page.number,
                                              'num': num,
                                              'pre_page': pre_page,
                                              'next_page': next_page, })

    return render(request, 'index.html')
# 删除
def book_delete(request,id):
    Book.objects.get(id=id).delete()
    return redirect('index')
# 注册
def logins(request):
    if request.method=='POST':
       username=request.POST.get('username')
       password=request.POST.get('password')
       User.objects.create_user(uname=username,upwd=password)
       return redirect('index')
    return render(request,'logins.html')
# 登录
def enter(request):
    if request.method=='POST':
       uname=request.POST.get('uname')
       upwd=request.POST.get('upwd')
       user=authenticate(uname=uname,upwd=upwd)
       if user is not None:
           login(request,user)
           return redirect('index')
       else:
           return render(request,'enter.html',{'error':'用户名或密码错误'})
    return render(request,'enter.html')

